﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading;

namespace BL
{
    [Serializable()]
    public class cLocationManager
    {
        public delegate void LocationUpdateLisner(Point p);
        public event LocationUpdateLisner LocationUpdate;

        public delegate void DataReceivedListener(PLAYER_STATUS status);
        public event DataReceivedListener DataReceived;

        Point m_CurrLocation;
        public Point CurrLocation
        {
            get { return m_CurrLocation; }
            set
            {
                if (m_CurrLocation != value)
                {
                    PrevLocation = m_CurrLocation;
                    m_CurrLocation = value;
                    if (LocationUpdate != null)
                        LocationUpdate(m_CurrLocation);
                }
            }
        }

        public Point PrevLocation { get; set; }

        [field: NonSerialized] cUDPConnectionHandler m_ConnectionHandler = null;
        public cUDPConnectionHandler ConnectionHandler
        {
            get { return m_ConnectionHandler; }
            set { m_ConnectionHandler = value; }
        }

        public cLocationManager(int startPort, int id)
        {
            RefreshConnection(startPort, id);
        }

        void ConnectionHandler_DataReceived(byte[] data)
        {
            //const int coordLength = 7;
            //const int coordPrecision = 3;
            string stringData = Encoding.ASCII.GetString(data);

            int nStartIndex = stringData.IndexOf("<");
            int nEndIndex = stringData.IndexOf(">");

            if ((nStartIndex != -1) && (nEndIndex != -1))
            {
                stringData = stringData.Remove(0, nStartIndex + 1);
                stringData = stringData.Remove(nEndIndex - 1);

                string[] splitted = stringData.ToString().Split(';');

                foreach (string field in splitted)
                {
                    string identifier = field.Split('=')[0].ToLower();
                    string value = field.Split('=')[1].ToLower();
                     
                    if (identifier == "playerdatacommand:location")
                    {
                        string lon, lat;


                        lon = handleCoords(value.Split(',')[0], 32.130d, 1000000); //For Base Map
                        lat = handleCoords(value.Split(',')[1], 34.787d, 1000000); //For Base Map

                        CurrLocation = new Point(int.Parse(lon), int.Parse(lat));
                    }
                    else if (identifier == "status")
                        DataReceived((PLAYER_STATUS)Enum.Parse(typeof(PLAYER_STATUS), value.ToUpper()));
                }
            }
        }

        private string handleCoords(string str, double reduce, double multiply)
        {
            double number = double.Parse(str);
            number = number - reduce;
            number = number * multiply;

            return number.ToString().Remove(number.ToString().IndexOf("."));


             //return str;
            
            ////32.123456 7891011

            //// get the 6th digit and so forth
            //try
            //{
            //    if (str.IndexOf(".") + startFrom >= str.Length)
            //        str = "0";
            //    else
            //    {
            //        if (str.IndexOf(".") + startFrom + len > str.Length)
            //            len = str.Length - str.IndexOf(".") - startFrom;

            //        str = str.Substring(str.IndexOf(".") + startFrom, len);
            //    }

            //    while (str.Length > len)
            //    {
            //        str += "0";
            //    }
            //    return str;
            //}
            //catch (Exception e)
            //{
            //    return "0000";
            //}
        }
        

        public void RefreshConnection(int startPort, int id)
        {
            if (ConnectionHandler == null)
            ConnectionHandler = new cUDPConnectionHandler();
            ConnectionHandler.StartListening(startPort + id);
            ConnectionHandler.DataReceived += ConnectionHandler_DataReceived;
        }
    }
}


//   string data = "<Location=100,200;status=ALIVE;HasFlag=FALSE>";
//             Point CurrLocation;

//             int nStartIndex = data.IndexOf("<");
//             int nEndIndex = data.IndexOf(">");

//             if ((nStartIndex != -1) && (nEndIndex != -1))
//             {
//                 data = data.Remove(0, nStartIndex + 1);
//                 data = data.Remove(nEndIndex - 1);

//                string[] splitted = data.ToString().Split(';');

//                foreach (string field in splitted)
//                {
//                    string identifier = field.Split('=')[0].ToLower();
//                    string value = field.Split('=')[1].ToLower();

//                    if (identifier == "location")
//                    {
//                        CurrLocation = new Point(int.Parse(value.Split(',')[0]), int.Parse(value.Split(',')[1]));
//                    }
//                    else if (identifier == "status")
//                    {

//                    }
//                    else if (identifier == "hasflag")
//                    {

//                    }
//                }
//}
